//
//  SWImageTransferViewController.m
//  ImageWorkshop
//
//  Created by Runli Song on 2023/11/30.
//  Copyright © 2023 James Song. All rights reserved.
//

#import "SWImageTransferViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "SendFileViewController.h"
#import "ReciveFileViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface SWImageTransferViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIImageView *mainImage;

@property (nonatomic, strong) UILabel *tipsLabel;

@property (nonatomic, strong) UIButton *entryBtn;

@property (nonatomic, strong) UIButton *doneBtn;

@end

@implementation SWImageTransferViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"图片传输";
    
    [self setRightItemWithTitle:@"保存" selector:@selector(saveImage) color:MainThemeColor];
    
    [self.view addSubview:self.doneBtn];
    [self.doneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(20));
        make.bottom.right.equalTo(@(-20));
        make.height.equalTo(@(50));
    }];
    
    [self.view addSubview:self.entryBtn];
    [self.entryBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(self.doneBtn);
        make.bottom.equalTo(_doneBtn.mas_top).offset(-20);
    }];
    
    [self.view addSubview:self.mainImage];
    [self.mainImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(@(20));
        make.right.equalTo(@(-20));
        make.bottom.equalTo(self.entryBtn.mas_top).offset(-20);
    }];
    
    [self.mainImage addSubview:self.tipsLabel];
    [self.tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(@(0));
    }];
}


-(void)onClickLeft{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(void)onClickSend{
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    __weak typeof(self) ws = self;
    UIAlertAction *photosAction = [UIAlertAction actionWithTitle:@"本地相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [ws accessLocaResource:(NSString *)kUTTypeImage];
    }];
    [alertView addAction:photosAction];
    UIAlertAction *videosAction = [UIAlertAction actionWithTitle:@"本地视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [ws accessLocaResource:(NSString *)kUTTypeMovie];
    }];
    [alertView addAction:videosAction];
   
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertView addAction:cancelAction];
    [self presentViewController:alertView animated:YES completion:nil];
}

-(void)onClickReceive{
    ReciveFileViewController *sendFileVC = [[ReciveFileViewController alloc] initWithFileCallback:^(NSString *filePath) {
        if ([filePath containsString:@"JPG"]) {
            self.mainImage.image = [UIImage imageWithContentsOfFile:filePath];
            self.tipsLabel.hidden = YES;
        }else{
            [self saveVideoToCameraRoll:[NSURL URLWithString:filePath]];
        }
       
    }];
    [self.navigationController pushViewController:sendFileVC animated:YES];
}

-(void)saveImage{
    if (self.mainImage.image) {
        [UIImage saveImageToPhotoAlbum:self.mainImage.image];
    }else{
        [SVProgressHUD showErrorWithStatus:@"请先传输图片"];
    }
}


//访问本地资源
- (void)accessLocaResource:(NSString *)type
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.mediaTypes =  [[NSArray alloc] initWithObjects:type, nil];
        [self presentViewController:picker animated:YES completion:nil];
    }
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //因为相册中的文件不能直接访问，所以需要将选取到的资源存储到临时文件夹中，再发送
    NSString *mediaType = (NSString *)info[UIImagePickerControllerMediaType];
    [SVProgressHUD show];
    __weak typeof(self) ws = self;
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //存储图片文件
            UIImage *tempImage = (UIImage *)info[UIImagePickerControllerOriginalImage];
            NSData *pngData = UIImageJPEGRepresentation(tempImage, 1.0);
            NSDateFormatter *inFormat = [NSDateFormatter new];
            [inFormat setDateFormat:@"yyMMdd-HHmmss"];
            NSString *imageName = [NSString stringWithFormat:@"image-%@.JPG", [inFormat stringFromDate:[NSDate date]]];
            NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:imageName];
            [pngData writeToFile:tempPath atomically:YES];
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                [ws dismissViewControllerAnimated:YES completion:^{
                    SendFileViewController *sendFileVC = [[SendFileViewController alloc] initWithFilePath:tempPath];
                    [ws.navigationController pushViewController:sendFileVC animated:YES];
                }];
            });
        });
    } else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //存储视频文件
            NSURL *videoUrl = (NSURL *)info[UIImagePickerControllerMediaURL];
            NSData *videoData = [NSData dataWithContentsOfURL:videoUrl];
            NSDateFormatter *inFormat = [NSDateFormatter new];
            [inFormat setDateFormat:@"yyMMdd-HHmmss"];
            NSString *videoName = [NSString stringWithFormat:@"video-%@.%@", [inFormat stringFromDate:[NSDate date]], videoUrl.lastPathComponent];
            NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:videoName];
            [videoData writeToFile:tempPath atomically:YES];
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                ws.view.userInteractionEnabled = YES;
                [ws dismissViewControllerAnimated:YES completion:^{
                    SendFileViewController *sendFileVC = [[SendFileViewController alloc] initWithFilePath:tempPath];
                    [ws.navigationController pushViewController:sendFileVC animated:YES];
                }];
            });
        });
    }
}

- (void)saveVideoToCameraRoll:(NSURL *)videoURL {
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    // 检查是否有相册访问权限
    if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized ||
        [ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusNotDetermined) {

        // 保存视频到相册
        [library writeVideoAtPathToSavedPhotosAlbum:videoURL completionBlock:^(NSURL *assetURL, NSError *error) {
            if (!error) {
                [SVProgressHUD showSuccessWithStatus:@"视频保存成功"];
            } else {
                [SVProgressHUD showErrorWithStatus:@"视频保存失败"];
            }
        }];
    } else {
        NSLog(@"没有相册访问权限");
    }
}


#pragma mark - getter

- (UIImageView *)mainImage{
    if(!_mainImage){
        _mainImage = [[UIImageView alloc] init];
        _mainImage.backgroundColor = UIColorFromHex(0xf0f0f0);
        _mainImage.userInteractionEnabled = YES;
        _mainImage.contentMode = UIViewContentModeScaleAspectFit;
  
    }
    return _mainImage;
}

- (UILabel *)tipsLabel{
    if(!_tipsLabel){
        _tipsLabel = [[UILabel alloc] init];
        _tipsLabel.text = @"暂无图片，请接收图片";
        _tipsLabel.textColor = MainThemeColor;
        _tipsLabel.userInteractionEnabled = YES;
    }
    return _tipsLabel;
}

- (UIButton *)entryBtn{
    if(!_entryBtn){
        _entryBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_entryBtn setTitle:@"发送文件" forState:UIControlStateNormal];
        [_entryBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        _entryBtn.backgroundColor = MainThemeColor;
        _entryBtn.layer.cornerRadius = 10;
        _entryBtn.layer.masksToBounds = YES;
        [_entryBtn addTarget:self action:@selector(onClickSend) forControlEvents:UIControlEventTouchUpInside];
    }
    return _entryBtn;
}

- (UIButton *)doneBtn{
    if(!_doneBtn){
        _doneBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_doneBtn setTitle:@"接收文件" forState:UIControlStateNormal];
        [_doneBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        _doneBtn.backgroundColor = MainThemeColor;
        _doneBtn.layer.cornerRadius = 10;
        _doneBtn.layer.masksToBounds = YES;
        [_doneBtn addTarget:self action:@selector(onClickReceive) forControlEvents:UIControlEventTouchUpInside];
    }
    return _doneBtn;
}

@end
